package eu.chargetime.ocpp.jsonserverimplementation.config;

import com.google.gson.Gson;
import eu.chargetime.ocpp.AuthenticationException;
import eu.chargetime.ocpp.ServerEvents;
import eu.chargetime.ocpp.jsonserverimplementation.server.ISessionStoreService;
import eu.chargetime.ocpp.model.SessionInformation;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.UUID;

@Configuration
@Getter
@Slf4j
public class ServerEventConfig {

    @Bean
    public ServerEvents createServerCoreImpl() {
        return getNewServerEventsImpl();
    }

    @Resource
    private ISessionStoreService sessionStoreService;

    private ServerEvents getNewServerEventsImpl() {
        return new ServerEvents() {
            final Gson gson = new Gson();

            @Override
            public void authenticateSession(final SessionInformation information, final String username, final byte[] password) throws AuthenticationException {
                log.info("[authenticateSession],TODO  这里可以做权限校验");
            }

            @Override
            public void newSession(UUID sessionIndex, SessionInformation information) {
                log.info("[newSession],新会话,sessionIndex:{},information:{}", gson.toJson(sessionIndex), gson.toJson(information));
                // sessionIndex is used to send messages.
                System.out.println("New session " + sessionIndex + ": " + information.getIdentifier());

                // 保存会话
                sessionStoreService.put(sessionIndex.toString(),sessionIndex);
            }

            @Override
            public void lostSession(UUID sessionIndex) {
                log.info("[lostSession],会话断开,sessionIndex:{}", gson.toJson(sessionIndex));
                System.out.println("Session " + sessionIndex + " lost connection");
                // 移除会话
                sessionStoreService.remove(sessionIndex.toString());
            }
        };
    }


}
